package cn.hackcloud.mutithread.mutilthread.lock6;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyService {
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	public void read() {
		try {
			lock.readLock().lock();
			System.out.println("获得读锁：" + Thread.currentThread().getName() + "_" + System.currentTimeMillis());
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.readLock().unlock();
		}

	}

	public void write() {
		try {
			lock.writeLock().lock();
			System.out.println("获得写锁：" + Thread.currentThread().getName() + "_" + System.currentTimeMillis());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.writeLock().unlock();
		}

	}

	public static void main(String[] args) {
		MyService myService = new MyService();
		Thread a = new Thread(new Runnable() {

			@Override
			public void run() {
				myService.read();

			}
		});
		Thread b = new Thread(new Runnable() {

			@Override
			public void run() {
				myService.write();
			}
		});
		a.start();
		b.start();
	}
}
